﻿using AMapPlugin.Dtos;
using AMapPlugin.HttpApi;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Runtime;
using System.Text;
using System.Threading.Tasks;

namespace AMapPlugin
{
    public class AmapPlugin : IAmapPlugin
    {
        private IAmapApi _httpApi;
        public AmapPlugin(IAmapApi httpApi)
        {
            _httpApi = httpApi;
        }

        /// <summary>
        /// 获取IP信息
        /// </summary>
        /// <param name="ip"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public async Task<IpInfo> GetIpInfo(string ip)
        {
            IpInfo ipInfo;
            if (IsPrivateIp(ip))
            {
                ipInfo = new IpInfo
                {
                    Province = "局域网",
                    Status = "1",
                };
                return ipInfo;
            }

            ipInfo = await _httpApi.GetIpInfo(ip);
            if (!ipInfo.IsSuccess)
                throw new Exception($"IP定位失败，错误码：{ipInfo.Infocode}，错误信息;{ipInfo.Info}");
            return ipInfo;
        }

        /// <summary>
        /// 获取天气信息
        /// </summary>
        /// <param name="code">城市编码</param>
        /// <returns></returns>
        public async Task<WeatherInfo> GetWeather(string code)
        {
            AmapWeather response;
            response = await _httpApi.GetWeather(code);
            if (!response.IsSuccess)
                throw new Exception($"天气获取失败，错误码：{response.Infocode}，错误信息;{response.Info}");
            return response.Lives?.FirstOrDefault();
        }


        /// <summary>
        /// 判断 IP 地址是否为局域网地址
        /// </summary>
        /// <param name="ip">要判断的 IP 地址</param>
        /// <returns>如果是局域网地址则返回 true，否则返回 false</returns>
        private bool IsPrivateIp(string ip)
        {
            if (IPAddress.TryParse(ip, out var ipAddress))
            {
                byte[] bytes = ipAddress.GetAddressBytes();
                // 特殊判断：0.0.0.1
                if (ip == "0.0.0.1")
                {
                    return true;
                }
                // IPv4 判断局域网网段
                if (ipAddress.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                {
                    return (bytes[0] == 10) || // 10.0.0.0 - 10.255.255.255
                           (bytes[0] == 172 && bytes[1] >= 16 && bytes[1] <= 31) || // 172.16.0.0 - 172.31.255.255
                           (bytes[0] == 192 && bytes[1] == 168); // 192.168.0.0 - 192.168.255.255
                }

                // IPv6 判断局域网地址 (例如：fc00::/7 为本地地址)
                if (ipAddress.AddressFamily == System.Net.Sockets.AddressFamily.InterNetworkV6)
                {
                    return ipAddress.IsIPv6SiteLocal || ipAddress.IsIPv6LinkLocal;
                }
            }

            return false;
        }
    }
}
